import { defineStore } from "pinia"
import { asyncRoutes, basicRoutes } from '@/router/routes'
export interface routerType {
  children: object[];
  meta: {
    role: string;
  };
}

function hasPermission(route: { meta: { role: any } }, role: any[]) {
  const routeRole = route.meta?.role ? route.meta.role : []
  if (!role.length || !routeRole.length) {
    return false
  }
  return role.some((item) => routeRole.includes(item))
}

function filterAsyncRoutes(routes: any[], role: any[]) {
  const ret: object[] = []
  routes.forEach((route: { meta: { role: string }, children: object[] }) => {
    if (hasPermission(route, role)) {
      const curRoute: routerType = {
        ...route,
        children: []
      }
      if (route.children && route.children.length) {
        curRoute.children = filterAsyncRoutes(route.children, role)
      } else {
        Reflect.deleteProperty(curRoute, 'children')
      }
      ret.push(curRoute)
    }
  })
  return ret
}

export const usePermissionStore = defineStore({
  id: 'permission',
  state: () => ({
    accessRoutes: []
  }),
  getters: {
    routes(): any {
      return basicRoutes.concat(this.accessRoutes)
    },
  },
  actions: {
    generateRoutes(role = []) {
      const accessRoutes: any = filterAsyncRoutes(asyncRoutes, role)
      this.accessRoutes = accessRoutes
      return accessRoutes
    },
  },
})
